package com.example.event;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @author frank
 * @date 2019-09-20 17:32
 * @desc
 **/

@Configuration
@EnableConfigurationProperties({ConfigProperties.class, PoolConfigProperties.class})
public class EventAutoConfigure implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private Environment environment;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        Boolean disruptor = environment.getProperty("event.disruptor", Boolean.class, false);
        int poolSize = environment.getProperty("event.pool.size", Integer.class, 5);
        int poolMaxSize = environment.getProperty("event.pool.max-size", Integer.class, 10);
        int poolKeepAlive = environment.getProperty("event.pool.keep-alive", Integer.class, 60);
        int poolAwaitTime = environment.getProperty("event.pool.await-time", Integer.class, 60);
        int queueSize = environment.getProperty("event.pool.queue-size", Integer.class, 32768);
        //根据配置选择不同的实现
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(EventBusImpl.class);
        if (disruptor) {
            builder = BeanDefinitionBuilder.genericBeanDefinition(DisruptorEventBusImpl.class);
        } else {
            builder.addPropertyValue("poolMaxSize", poolMaxSize);
            builder.addPropertyValue("poolKeepAlive", poolKeepAlive);
        }
        builder.addPropertyValue("queueSize", queueSize);
        builder.addPropertyValue("poolSize", poolSize);
        builder.addPropertyValue("poolAwaitTime", poolAwaitTime);

        registry.registerBeanDefinition("eventBus", builder.getBeanDefinition());
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

}